import React, {useCallback, useEffect, useRef, useState} from 'react';
import {View, Text} from '@tarojs/components';
import {Button, Cell, CellGroup, Grid, GridItem, Icon, Image} from "@antmjs/vantui";
import Utils from "@/utils/common";
import RouthPath from "@/common/RouthPath";
import AssetImage from "@/common/AssetImage";
import LocalData from "@/common/local_data";
import {getUserInfoApi} from "@/common/apis/home_datasource";
import {InvoiceParams, UserinfoModel} from "@/common/apis/model";
import ShowUtils from "@/utils/show_utils";
import LocalUtils from "@/utils/local_utils";
import {OrderStatus, OrderStatusInfo} from "@/common/enums";
import {usePullDownRefresh, useTabItemTap} from "@tarojs/taro";
import EventUtils from "@/utils/event_utils";
import KefuDialog from "@/components/kefu_dialog";


definePageConfig({
  navigationBarTitleText: '我的',
  enablePullDownRefresh: true,
  enableShareAppMessage: true,
  enableShareTimeline: true,
})

const Mine = () => {
  const [userInfo, setUserInfo] = useState<UserinfoModel>();
  const getData = useCallback((isRefresh) => {
    getUserInfoApi(isRefresh).then((info) => {
      if (info) {
        LocalUtils.setUserinfo(info.username, info.avatar, info.mobile, info.authentication, info.realname, info.idNo, info.company)
        LocalUtils.setUserId(info.id)
        setUserInfo(info)
      }
    });
  }, []);
  const refreshUserinfo = useCallback(() => {
    getData(false)
  }, [getData]);

  const goUrl = useCallback((data) => {
    setTimeout(() => {
      Utils.navigateTo({
        url: data
      })
    }, 1000)
  }, []);

  useEffect(() => {
    getData(false)
    const eventCenter = EventUtils.on(EventUtils.UserInfo, refreshUserinfo)
    return () => {
      eventCenter()
    };
    //把info 放到 state 中
  }, [getData, goUrl, refreshUserinfo]);
  usePullDownRefresh(() => {
    getData(true)
  })
  useTabItemTap((payload) => {
    Utils.goEditProfile()
  });

  const orderCategories = [
    OrderStatusInfo[OrderStatus.WAIT_ACCEPT],
    OrderStatusInfo[OrderStatus.PENDING],
    OrderStatusInfo[OrderStatus.WAIT_CONFIRMATION],
    OrderStatusInfo[OrderStatus.WAIT_PAYMENT],
    OrderStatusInfo[OrderStatus.FINISHED],
  ];

  const otherFunctions = [
    {text: '我的发票', icon: AssetImage.fplist},
    {text: '发票信息', icon: 'bill-o'},
    {text: '收件地址', icon: 'location-o'},
    // {text: '对账单', icon: 'orders-o'},
    {text: '资产管理', icon: 'balance-list-o'},
    {text: '预存记录', icon: 'records'},
    // {text: '账号安全', icon: 'lock'},
    {text: '课题组', icon: 'friends-o'},
    {text: '检测结果', icon: 'search'},
    {text: '实名认证', icon: AssetImage.smrz},
    {text: '个人信息', icon: AssetImage.tab4},
    {text: '联系客服', icon: "service"},
    // {text: '个人名片', icon: 'contact'},
    // {text: '联系我们', icon: 'phone-o'},
  ];

  const renderIsV = useCallback(() => {
    if (LocalUtils.isVIdCard()) {
      return <Text style={{color: '#98FB98'}}>(已认证)</Text>
    } else {
      return <Text style={{color: 'red'}}>(未认证)</Text>
    }
  }, [userInfo?.idNo]);

  const kefuDialogRef = useRef(null);
  const openDialog = () => {
    // 通过 ref 调用子组件的 setShow 方法
    if (kefuDialogRef.current) {
      kefuDialogRef.current.setShow(true);
    }
  };

  return (
    <View style={{backgroundColor: '#f2f2f2', minHeight: '100vh'}}>
      {/* 个人信息栏 */}
      {
        userInfo ? <View>
          <Cell
            style={{backgroundColor: '#517be9'}}
            renderIcon={<Image
              radius='5px'
              src={ShowUtils.getImageUrl(ShowUtils.getImage(userInfo.avatar))}
              style={{width: '50px', height: '50px', marginBottom: '10px'}}
              mode='aspectFill' // 确保图片填充圆形区域
            />}
            renderTitle={<View
              style={{display: 'flex', flexDirection: 'column', alignItems: 'flex-start', marginLeft: '10px'}}
            >
              <View>
                <Text style={{
                  fontSize: '18px',
                  color: '#fff'
                }}
                >{ShowUtils.showName(userInfo.username, userInfo.realname)}</Text>
                {
                  renderIsV()
                }
              </View>
              <Text style={{fontSize: '14px', color: '#fff'}}>{ShowUtils.getDefault(userInfo.mobile)}</Text>
              <Text style={{fontSize: '14px', color: '#fff'}}>用户ID:{ShowUtils.getDefault(userInfo.id)}</Text>
            </View>}
          >
            <Button size='normal' onClick={() => {
              const p: InvoiceParams = {
                type: 0
              }
              Utils.navigateTo({
                url: Utils.getUrlWithObject(RouthPath.applyRecharge, p)
              })
            }}
            >开发票</Button>
          </Cell>

          {/* 余额、优惠券、积分 */}
          <View style={{
            backgroundColor: '#fff',
            display: 'flex',
            justifyContent: 'space-around',
            padding: '15px 0',
            marginTop: '10px'
          }}
          >
            <View style={{display: 'flex', flexDirection: 'column', alignItems: 'center'}} onClick={() => {
              Utils.navigateTo({
                url: RouthPath.assetsManager
              })
            }}
            >
              <Text style={{fontSize: '16px', color: '#333'}}>{ShowUtils.getDefaultPrice(userInfo.balance)}</Text>
              <Text style={{fontSize: '12px', color: '#666'}}>余额</Text>
            </View>
            <View style={{display: 'flex', flexDirection: 'column', alignItems: 'center'}} onClick={() => {
              Utils.navigateTo({
                url: RouthPath.assetsManager
              })
            }}
            >
              <View>
                <Text style={{fontSize: '16px', color: 'red'}}>{ShowUtils.getDefaultPrice(userInfo.debtLimitUse)}</Text>
                <Text
                  style={{fontSize: '16px', color: '#333'}}
                >{`/${ShowUtils.getDefaultPrice(userInfo.debtLimit)}`}</Text>
              </View>
              <Text style={{fontSize: '12px', color: '#666'}}>信用分</Text>
            </View>
            <View style={{display: 'flex', flexDirection: 'column', alignItems: 'center'}} onClick={() => {
              Utils.navigateTo({
                url: RouthPath.couponList
              })
            }}
            >
              <Text style={{fontSize: '16px', color: '#333'}}>{ShowUtils.getDefault(userInfo.coupons, '0')}</Text>
              <Text style={{fontSize: '12px', color: '#666'}}>优惠券</Text>
            </View>
          </View>

          <CellGroup style={{marginTop: '10px'}}>
            <Cell
              title='订单管理'
              isLink
              value='全部订单'
              onClick={() => {
                LocalData.currentIndexOrder = 0;
                Utils.switchTab({
                  url: RouthPath.tabbarOrder
                })
              }}
            >
            </Cell>
          </CellGroup>
          <View style={{
            backgroundColor: '#fff',
            display: 'flex',
            justifyContent: 'space-around',
            padding: '20px 0',
            marginTop: '0px'
          }}
          >
            {orderCategories.map((category, index) => (
              <View
                key={category.text}
                style={{display: 'flex', flexDirection: 'column', alignItems: 'center'}}
                onClick={() => {
                  LocalData.currentIndexOrder = index + 1;
                  Utils.switchTab({
                    url: RouthPath.tabbarOrder
                  })
                }}
              >
                <Icon name={category.icon} size='30px'/>
                <Text style={{fontSize: '12px', color: '#666', marginTop: '5px'}}>{category.text}</Text>
              </View>
            ))}
          </View>
        </View> : null
      }
      <CellGroup style={{marginTop: '10px'}}>
        <Cell
          title='其他功能'
        >
        </Cell>
      </CellGroup>

      {/* 其他功能 */}
      <CellGroup style={{padding: '20px 0'}}>
        <Grid border={false} gutter={10}>
          {
            otherFunctions.map((func) => (
              <GridItem key={func.text} icon={func.icon} text={func.text} onClick={() => {
                if (func.icon === 'bill-o') {
                  Utils.navigateTo({
                    url: RouthPath.faPiaoList
                  })
                } else if (func.icon === 'location-o') {
                  Utils.navigateTo({
                    url: RouthPath.addressList
                  })
                } else if (func.icon === 'balance-list-o') {
                  Utils.navigateTo({
                    url: RouthPath.assetsManager
                  })
                } else if (func.icon === 'records') {
                  Utils.navigateTo({
                    url: RouthPath.applyRecord
                  })
                } else if (func.icon === 'friends-o') {
                  Utils.navigateTo({
                    url: RouthPath.researchTeam
                  })
                } else if (func.icon === 'search') {
                  Utils.navigateTo({
                    url: RouthPath.searchStatement
                  })
                } else if (func.icon === AssetImage.smrz) {
                  if (LocalUtils.isVIdCard()) {
                    Utils.showErrorToast('已认证')
                    return;
                  }
                  Utils.navigateTo({
                    url: RouthPath.realInfoVerify
                  })
                } else if (func.icon === AssetImage.tab4) {
                  Utils.navigateTo({
                    url: RouthPath.accountSafe
                  })
                } else if (func.icon === AssetImage.fplist) {
                  Utils.navigateTo({
                    url: RouthPath.invoiceListPage
                  })
                } else if (func.icon === 'service') {
                  openDialog()
                }
              }}
              />
            ))
          }
        </Grid>
      </CellGroup>
      <View style={{
        display: "flex",
        flexDirection: 'row',
        justifyContent: 'center',
        padding: '24px',
      }}
      >
        <Button size='large' type='info' hairline plain round onClick={() => {
          Utils.modal("提示", "确定要退出登录吗？", true, (ok) => {
            if (ok) {
              LocalUtils.exitLogin();
              Utils.reLaunch({
                url: RouthPath.login
              }, 3)
            }
          })
        }}
        >退出登录</Button>
        <KefuDialog ref={kefuDialogRef}/>
      </View>

    </View>
  );
};

export default Mine;

